package com.xpsoft.oa.service.project.impl;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.project.ProjectExpensesDao;
import com.xpsoft.oa.dao.project.ProjectExpensesInfoDao;
import com.xpsoft.oa.model.project.ProjectExpenses;
import com.xpsoft.oa.model.project.ProjectExpensesInfo;
import com.xpsoft.oa.model.system.FileAttach;
import com.xpsoft.oa.service.project.ProjectExpensesService;
import com.xpsoft.oa.service.system.FileAttachService;

public class ProjectExpensesServiceImpl extends BaseServiceImpl<ProjectExpenses> implements ProjectExpensesService{
	private ProjectExpensesDao dao;
	@Autowired
	private ProjectExpensesInfoDao projectExpensesInfoDao;
	@Autowired
	private FileAttachService fileAttachService;
	public ProjectExpensesServiceImpl(ProjectExpensesDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveProjectExpenses(ProjectExpenses projectExpenses,
			String dataList) {
		Boolean isNew = true;//新增标志
		if(projectExpenses.getId()!=null){
			isNew = false;
		}
		dao.save(projectExpenses);
		if(StringUtils.isNotBlank(dataList)){
			List<ProjectExpensesInfo> projectExpensesInfoList = JsonUtil.fromJsonTypesWithDate(dataList,
					new TypeToken<List<ProjectExpensesInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(ProjectExpensesInfo projectExpensesInfo:projectExpensesInfoList){
					if(projectExpensesInfo.getId()!=null){//修改的记录
						idList.add(projectExpensesInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					projectExpensesInfoDao.deleteProjectExpensesInfos(projectExpenses.getId(), idList);
				}
			}
			for(ProjectExpensesInfo projectExpensesInfo:projectExpensesInfoList){
				projectExpensesInfo.setProjectExpenses(projectExpenses);
				if(StringUtils.isNotBlank(projectExpensesInfo.getFileIds())){
					Set<FileAttach> fileSet = new HashSet<FileAttach>();
					String fileIds[] = projectExpensesInfo.getFileIds().split("\\|");
					projectExpensesInfo.getFileAttachs().clear();
					for(String fileId:fileIds){
						fileSet.add(fileAttachService.get(Long.valueOf(fileId)));
					}
					projectExpensesInfo.getFileAttachs().addAll(fileSet);
				}
				projectExpensesInfoDao.save(projectExpensesInfo);
			}
		}
	}

}